{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4.4. Profiling the memory usage of your code with memory_profiler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext memory_profiler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile memscript.py\n",
    "def my_func():\n",
    "    a = [1] * 1000000\n",
    "    b = [2] * 9000000\n",
    "    del b\n",
    "    return a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "*** Profile printout saved to text file mprof0.\n"
     ]
    }
   ],
   "source": [
    "from memscript import my_func\n",
    "%mprun -T mprof0 -f my_func my_func()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Line #  Mem usage    Increment   Line Contents\n",
      "================================================\n",
      "   1     93.4 MiB      0.0 MiB   def my_func():\n",
      "   2    100.9 MiB      7.5 MiB       a = [1] * 1000000\n",
      "   3    169.7 MiB     68.8 MiB       b = [2] * 9000000\n",
      "   4    101.1 MiB    -68.6 MiB       del b\n",
      "   5    101.1 MiB      0.0 MiB       return a\n"
     ]
    }
   ],
   "source": [
    "print(open('mprof0', 'r').read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "peak memory: 101.20 MiB, increment: 7.77 MiB\n"
     ]
    }
   ],
   "source": [
    "%%memit import numpy as np\n",
    "np.random.randn(1000000)"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
